﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BencodeNET.Objects;
using BencodeNET.Parsing;
using BencodeNET.Torrents;
using LocalHtmlOperationNew.common;
using Ookii.Dialogs.WinForms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string getTimeResult = HttpHelp.Get("http://quan.suning.com/getSysTime.do");
            TimeInfo BJtime = new TimeInfo();
            if (getTimeResult != null && getTimeResult.Trim() != "")
            {
                BJtime = ConvertJson.FromJSON<TimeInfo>(getTimeResult);
            }
            if (BJtime == null || BJtime.sysTime2 == null)
            {
                BJtime = new TimeInfo() { sysTime2 = DateTime.MinValue };
            }
            if (BJtime.sysTime2 > Convert.ToDateTime("2023-01-2 17:55:22"))
            {
                MessageBox.Show("时间过期");
                this.Close();
                return;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var dialog = new VistaFolderBrowserDialog()
            {
                Description = "选择操作目录"
            };
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "选择不能为空", "");
                    return;
                }
                label2.Text = dialog.SelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var fileNames = FileUtilHelper.GetFileNames(label2.Text, "*.torrent", false);
            if (fileNames.Length > 0)
            {
                richTextBox1.Text = "";
                foreach (var fileName in fileNames)
                {
                    // Parse torrent by specifying the file path
                    var parser = new BencodeParser(); // Default encoding is Encoding.UTF8, but you can specify another if you need to
                    //Torrent torrent = parser.Parse<Torrent>(fileName);
                    Stream stream = FileToStream(fileName);
                    // Or parse a stream
                    Torrent torrent = parser.Parse<Torrent>(stream);
                    // Calculate the info hash
                    string infoHash = torrent.GetInfoHash();
                    // "B415C913643E5FF49FE37D304BBB5E6E11AD5101"
                    // or as bytes instead of a string
                    byte[] infoHashBytes = torrent.GetInfoHashBytes();
                    // Get Magnet link
                    string magnetLink = torrent.GetMagnetLink();
                    // magnet:?xt=urn:btih:1CA512A4822EDC7C1B1CE354D7B8D2F84EE11C32&dn=ubuntu-14.10-desktop-amd64.iso&tr=http://torrent.ubuntu.com:6969/announce&tr=http://ipv6.torrent.ubuntu.com:6969/announce
                    WriteLog(magnetLink);
                    // Convert Torrent to its BDictionary representation
                    BDictionary bdictinoary = torrent.ToBDictionary();
                }
            }

            CreateTextAndWrite();
        }

        private void CreateTextAndWrite()
        {
            if (!string.IsNullOrEmpty(richTextBox1.Text))
            {
                string content = richTextBox1.Text;
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
                string saveFilePath = Path.Combine(label2.Text, fileName);
                //判断是否已经有了这个文件
                if (!System.IO.File.Exists(saveFilePath))
                {
                    //没有则创建这个文件
                    FileStream fs1 = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write);//创建写入文件 
                    //设置文件属性为隐藏
                    System.IO.File.SetAttributes(saveFilePath, FileAttributes.Hidden);
                    StreamWriter sw = new StreamWriter(fs1);
                    sw.WriteLine(content);//开始写入值
                    sw.Close();
                    fs1.Close();
                    MessageBox.Show("写入txt内容完成");
                }
                else
                {
                    FileStream fs = new FileStream(saveFilePath, FileMode.Open, FileAccess.Write);
                    System.IO.File.SetAttributes(saveFilePath, FileAttributes.Hidden);
                    StreamWriter sr = new StreamWriter(fs);
                    sr.WriteLine(content);//开始写入值
                    sr.Close();
                    fs.Close();
                   MessageBox.Show("写入txt内容完成");
                }
            }
        }

        /// <summary> 
        /// 从文件读取 Stream //转载请注明来自 http://www.uzhanbao.com
        /// </summary> 
        public Stream FileToStream(string fileName)
        {
            // 打开文件 
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            // 读取文件的 byte[] 
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            // 把 byte[] 转换成 Stream 
            Stream stream = new MemoryStream(bytes);
            return stream;
        }

        private void WriteLog(string str)
        {
            this.richTextBox1.Text += $"\n{str}";
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            richTextBox1.Focus();
            richTextBox1.Select(richTextBox1.Text.Length, 0);
            richTextBox1.ScrollToCaret();
        }
    }
}
